package com.android.antelopeapp.activity;

import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

import com.android.antelopeapp.R;
import com.android.antelopeapp.common.GlobalResource;
import com.android.antelopeapp.common.ImageTool;
import com.android.antelopeapp.constant.AppConfig;

import java.io.File;
import java.io.IOException;

/**
 * Created by phk on 2015/1/3.
 *
 */
public class UploadBPicActivity extends BaseActivity {
    public static final String TAG = UploadBPicActivity.class.getName();
    /**
     * 从相册获取本地图片文件
     */
    public static final int RESULT_LOAD_IMAGE = 201;
    /**
     * 使用相机获取图片
     */
    public static final int RESULT_CAPTURE_PIC = 202;
    /**
     * 获取ImageTags
     * */
    public static int REQUEST_IMAGE_TAGS = 203;
    /**
     * 发布美图
     * */
    public static int REQUEST_UPLOAD_TAGABELIMAGE = 204;
    public static String REQ_TYPE_CODE = "req_pic_type";
    /**
     * 请求图片的代码
     */
    public static String PIC_BITMAP = "pic_bitmap";
    public static String PIC_PATH = "pic_file_path";
    public static int MESSAGE_START_TAGIMAGEACTIVITY = 52;
    private ImageView mImg;
    private View mBackBtn;
    private View mNextBtn;
    private Bitmap mBitmap;
    private String mImgPath;
    private int mReqTypeCode;
    /**用于保存从相机获取图片时，文件的保存位置*/
    private String mCapPicPath;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mReqTypeCode = getIntent().getIntExtra(REQ_TYPE_CODE,-1);

        mImg = (ImageView) this.findViewById(R.id.choose_pic_img);
        mBackBtn = this.findViewById(R.id.choose_pic_back_btn);
        mNextBtn = this.findViewById(R.id.choose_pic_next_btn);

        mBackBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //关闭当前activity
                UploadBPicActivity.this.finish();
            }
        });
        mNextBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //下一步到达添加标签页面
                ActivityManager.startTagImageActivityForResult(UploadBPicActivity.this, REQUEST_IMAGE_TAGS);
            }
        });
        Handler handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                if (msg.what == MESSAGE_START_TAGIMAGEACTIVITY) {
                    if (mReqTypeCode == -1) {
                        finish();
                        Log.w(TAG, "mReqTypeCode=-1 未指定获取图片的方式");
                    } else if (mReqTypeCode == RESULT_CAPTURE_PIC) {
                        requestPicByCap();
                    } else if (mReqTypeCode == RESULT_LOAD_IMAGE) {
                        //打开系统图库，获取图片
                        Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                        startActivityForResult(i, RESULT_LOAD_IMAGE);
                    }
                }
                super.handleMessage(msg);
            }
        };
        handler.sendEmptyMessageDelayed(MESSAGE_START_TAGIMAGEACTIVITY,10);
    }

    @Override
    protected int getLayoutResource() {
        return R.layout.activity_choose_pic;
    }

    /**
     * 通过相机获取图片
     * 方法是指定相机照片存放的位置，然后通过路径获取文件
     * 若获取失败，则返回null
     * */
    private String requestPicByCap(){
        String state = Environment.getExternalStorageState();
        mCapPicPath = null;
        if(state.equals(Environment.MEDIA_MOUNTED)) {
            String tmpDir = AppConfig.PIC_STORAGE_DIR;
            File dir = new File(tmpDir);
            if (!dir.exists()) {
                dir.mkdir();
            }
            try {
                File file = new File(tmpDir, AppConfig.CAP_PIC_FILE_NAME);
                file.delete();
                if (!file.exists()) {
                    file.createNewFile();
                }

                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
                startActivityForResult(intent, RESULT_CAPTURE_PIC);

                mCapPicPath =  file.getAbsolutePath();
            } catch (IOException e) {
                e.printStackTrace();
                toast(R.string.photo_file_isnull);
            }
        }else{
            toast(R.string.common_msg_nosdcard);
        }
        return mCapPicPath;
    }

    /**
     * 通过图片path显示图片
     * */
    private void importImage(String picturePath){
        //导入图片
        Log.v(TAG, " width:" + mImg.getWidth() + " height:" + mImg.getHeight());
        mImgPath = picturePath;
        mBitmap = ImageTool.decodeSampledBitmapFromFile(picturePath, mImg.getWidth(), mImg.getHeight());
        GlobalResource.getInstance().cacheBitmap(GlobalResource.TAGED_IMG,mBitmap);
        mImg.setImageBitmap(mBitmap);
    }


    /**
     * 目前有三种情况会回调此函数
     * 1.选择通过相机获取图片之后
     * 2.通过选择图库中的图片之后
     * 3.将前两步所选择的图片加入标签之后
     * */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        try{
            if (resultCode == RESULT_OK) {
                //从图库获取图片
                if (requestCode == RESULT_LOAD_IMAGE) {
                    if (null == data) {
                        throw new Exception("返回的data不能为空!");
                    }
                    Uri selectedImage = data.getData();
                    String[] filePathColumn = {MediaStore.Images.Media.DATA};

                    Cursor cursor = getContentResolver().query(selectedImage,
                            filePathColumn, null, null, null);
                    cursor.moveToFirst();

                    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                    String picturePath = cursor.getString(columnIndex);
                    cursor.close();

                    // String picturePath contains the path of selected Image
                    //导入图片
                    importImage(picturePath);

                }
                //从相机获取图片
                else if (requestCode == RESULT_CAPTURE_PIC) {
                    if(mCapPicPath == null){
                        throw new Exception("图片的路径不能为空!");
                    }
                    importImage(mCapPicPath);
                }
                //图片已经添加标签，添加描述并上传
                else if(requestCode == REQUEST_IMAGE_TAGS){
                    ActivityManager.startShareBPicActivityForResult(this,REQUEST_UPLOAD_TAGABELIMAGE,data);
                }
                //上传成功
                else if(requestCode == REQUEST_UPLOAD_TAGABELIMAGE){
                    Log.d(this.getLocalClassName(),"美图上传成功，跳转到主页面.");
                    setResult(RESULT_OK);
                    finish();
                }
            }else{
                finish();
                Log.v(TAG,"onActivityResult finished . reqCode:"+requestCode+" resCode:"+resultCode+" data:"+data+" cappicPath:"+mCapPicPath);
            }
        }catch (Exception e){
            finish();
            Log.w(TAG,"onActivityResult finished with exception"+e.getMessage()
                    +"\n reqCode:"+requestCode+" resCode:"+resultCode+" data:"+data+" cappicPath:"+mCapPicPath);
        }
    }
}
